from django.shortcuts import render
from .models import ObservationRecord
import calendar
from datetime import date
from django.http import HttpResponse
from django.conf import settings
import os


def home(request):
    selected_year = request.GET.get('year', date.today().year)
    static_file_path = os.path.join(settings.BASE_DIR, f'static/calendar_{selected_year}.html')

    # 读取并返回静态HTML文件
    if os.path.exists(static_file_path):
        with open(static_file_path, 'r', encoding='utf-8') as file:
            return HttpResponse(file.read())

    return HttpResponse("没有找到该年份的静态页面", status=404)



def home_t(request):

    current_year = date.today().year
    selected_year = request.GET.get('year', current_year)
    selected_year = int(selected_year)

    # current_year = 2018
    # selected_year = 2013
    print(f'current_year:{(current_year)}')
    print(f'selected_year:{(selected_year)}')
    # 数据库中的最早年份
    earliest_record = ObservationRecord.objects.order_by('date').first()
    start_year = earliest_record.date.year if earliest_record else current_year

    # 年份范围：最早到当前年份
    year_range = list(range(start_year, current_year + 1))

    # 查询选定年份的观测记录
    observations = ObservationRecord.objects.filter(date__year=selected_year)
    day_status = {obs.date: obs.data_status for obs in observations}

    calendar_data = []
    for month in range(1, 13):
        _, num_days = calendar.monthrange(selected_year, month)
        month_data = []

        # 获取月份的第一天是星期几，并调整为星期日开头
        first_weekday, _ = calendar.monthrange(selected_year, month)
        month_data.extend([{'day': '', 'status': 'no_data'}] * first_weekday)  # 填充空白

        # 填充每一天的状态
        for day in range(1, num_days + 1):
            day_date = date(selected_year, month, day)
            status = day_status.get(day_date, 'no_data')  # 默认为无数据
            month_data.append({'day': day, 'status': status})

        # 分割为每周一行
        month_data = [month_data[i:i + 7] for i in range(0, len(month_data), 7)]
        calendar_data.append({'month_name': calendar.month_name[month], 'month_data': month_data})

    context = {
        'calendar_data': calendar_data,
        'year_range': year_range,
        'selected_year': selected_year,
    }
    return render(request, 'myindex3.html', context)

